
#include "bmpfile.h"
#include "shared\dbg.h"

namespace avlib{
BmpFile::BmpFile(const char *filename){
	m_filename = filename;
}

BmpFile::~BmpFile(){
}


bool BmpFile::save_bmp(HBITMAP bmp){

	HDC hdc;
	FILE*				fp=NULL;
	LPVOID				pBuf=NULL;
	BITMAPINFO			bmpInfo;
	BITMAPFILEHEADER	bmpFileHeader;

	bool result = true;

	do{

		hdc=GetDC(NULL);
		ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
		bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
		GetDIBits(hdc,bmp,0,0,NULL,&bmpInfo,DIB_RGB_COLORS);

		if(bmpInfo.bmiHeader.biSizeImage<=0)
			bmpInfo.bmiHeader.biSizeImage=bmpInfo.bmiHeader.biWidth*abs(bmpInfo.bmiHeader.biHeight)*(bmpInfo.bmiHeader.biBitCount+7)/8;

		if((pBuf=malloc(bmpInfo.bmiHeader.biSizeImage))==NULL)
		{
			//MessageBox(NULL,"Unable to Allocate Bitmap Memory"),_T("Error"),MB_OK|MB_ICONERROR);
			log("Unable to Allocate Bitmap Memory");
			result = false;break;
		}

		bmpInfo.bmiHeader.biCompression=BI_RGB;
		GetDIBits(hdc,bmp,0,bmpInfo.bmiHeader.biHeight,pBuf,&bmpInfo,DIB_RGB_COLORS);	

		if((fp=fopen(m_filename.c_str(),"wb"))==NULL)
		{
			//MessageBox(NULL,_T("Unable to Create Bitmap File"),_T("Error"),MB_OK|MB_ICONERROR);
			log("Unable to Create Bitmap File");
			result = false;break;
		}

		bmpFileHeader.bfReserved1=0;
		bmpFileHeader.bfReserved2=0;
		bmpFileHeader.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bmpInfo.bmiHeader.biSizeImage;
		bmpFileHeader.bfType='MB';
		bmpFileHeader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

		fwrite(&bmpFileHeader,sizeof(BITMAPFILEHEADER),1,fp);
		fwrite(&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp);
		fwrite(pBuf,bmpInfo.bmiHeader.biSizeImage,1,fp);

	}while(false);

	if(hdc)
		ReleaseDC(NULL,hdc);

	if(pBuf){
		free(pBuf);pBuf = 0;
	}
	if(fp){
		fclose(fp);fp = 0;
	}
	return result;

}


bool  BmpFile::save_bmp(BITMAPINFO &bmpInfo,void *pBits){

	BITMAPFILEHEADER	bmpFileHeader;
	FILE*				fp=NULL;
	bool result = false;

		if((fp=fopen(m_filename.c_str(),"wb"))==NULL)
		{
			//MessageBox(NULL,_T("Unable to Create Bitmap File"),_T("Error"),MB_OK|MB_ICONERROR);
			log("Unable to Create Bitmap File");
			return false;
		}

		bmpFileHeader.bfReserved1=0;
		bmpFileHeader.bfReserved2=0;
		bmpFileHeader.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bmpInfo.bmiHeader.biSizeImage;
		bmpFileHeader.bfType='MB';
		bmpFileHeader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);

		size_t sz = fwrite(&bmpFileHeader,sizeof(BITMAPFILEHEADER),1,fp);
		sz = fwrite(&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp);
		sz = fwrite(pBits,bmpInfo.bmiHeader.biSizeImage,1,fp);

		if(fp)
		fclose(fp);

		result = true;
		return result;
}
}